package com.zsk.okhttp;

import java.io.IOException;

import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
 * 
 * @author keke
 * @date 2020/04/23
 */
public class GetTask implements IGetTask {

    private OkHttpClient client;

    Request.Builder requestBuilder;
    HttpUrl.Builder urlBuilder;

    public GetTask(OkHttpClient client, String url) {
        super();
        this.client = client;
        this.requestBuilder = new Request.Builder();
        this.urlBuilder = HttpUrl.parse(url).newBuilder();
    }

    @Override
    public ResData run() throws IOException {
        requestBuilder.url(urlBuilder.build());
        Request request = requestBuilder.build();
        return ResData.of(client.newCall(request).execute());
    }

    @Override
    public void run(Callback callback) {
        Request request = requestBuilder.build();
        client.newCall(request).enqueue(callback);
    }

    @Override
    public IGetTask addQueryParam(String key, String value) {
        urlBuilder.addQueryParameter(key, value);
        return this;
    }

    @Override
    public IGetTask addHeader(String key, String value) {
        requestBuilder.addHeader(key, value);
        return this;
    }

}
